package logic

import (
	"context"
	"errors"
	"manuscript-service/models/mysql"

	"manuscript-service/manuscriptrpc/internal/svc"
	"manuscript-service/manuscriptrpc/manuscriptrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManuscriptAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManuscriptAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManuscriptAddLogic {
	return &ManuscriptAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加
func (l *ManuscriptAddLogic) ManuscriptAdd(in *manuscriptrpc.ManuscriptAddRequest) (*manuscriptrpc.ManuscriptAddResponse, error) {
	// todo: add your logic here and delete this line

	var manuscriptfind mysql.Manuscript

	begin := mysql.DB.Begin()

	if err := manuscriptfind.ManuscriptFindByTitle(mysql.DB, in.Title); err == nil {
		begin.Rollback()

		return nil, errors.New("该稿件已存在,不允许重复添加")
	}

	class := mysql.Class{
		Name: in.ClassName,
	}

	if err := class.ClassFindByName(mysql.DB, in.ClassName); err != nil {
		begin.Rollback()

		return nil, err
	}

	manuscript := &mysql.Manuscript{
		Title:   in.Title,
		Author:  in.Author,
		Content: in.Content,
		ClassId: int64(class.ID),
	}

	if err := manuscript.ManuscriptAdd(mysql.DB); err != nil {
		begin.Rollback()

		return nil, err
	}

	begin.Commit()

	return &manuscriptrpc.ManuscriptAddResponse{
		ManuscriptId: int64(manuscript.ID),
	}, nil
}
